package com.example.joysinfo.lkc;
import android.*;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.joysinfo.lkc.bean.Regidbean;
import com.example.joysinfo.lkc.bean.UploadBean;
import com.example.joysinfo.lkc.http.LikoushanApi;
import com.example.joysinfo.lkc.http.ResponseInterface;
import com.example.joysinfo.lkc.util.Sharedpreference;
import com.example.joysinfo.lkc.util.ToastUtil;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.List;


@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity implements BDLocationListener{

    public static final String APP_ID = "2882303761517594570";
    public static final String APP_KEY = "5581759487570";
    public static String xiaomiregid="";

    //百度定位
    public static LocationClient mLocationClient = null;
//    public BDLocationListener myListener = new MyLocationListener();

    private static String sign="";
    private String type="";
    private static String userid="";
    private String jingdu="";
    private String weidu="";
    private WebView content;
    private Handler mHandler = new Handler();
    private String first="1";
    private String chuanornot="0";
    private boolean granted;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        checkPermission(new PermissionActivity.CheckPermListener() {
//                            @Override
//                            public void superPermission() {
//                                ToastUtil.showToast(MainActivity.this, "申请定位权限成功");
//                            }
//                        }, "给我",
//                Manifest.permission.LOCATION_HARDWARE,
//                Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION);


        Intent intent = getIntent();
        String eid=intent.getStringExtra("msgID");


        sign = Sharedpreference.getSign();
        sign = parseByte2HexStr(sign.getBytes());
        userid= Sharedpreference.getUserid();
        type= Sharedpreference.getType();

        //初始化push推送服务
        if(shouldInit()) {
            MiPushClient.registerPush(this, APP_ID, APP_KEY);
        }
        if(TextUtils.isEmpty(eid)){
            loadhtml("http://60.232.1.10:83/likoushan_c/views/p/index.html?");
        }else {
            loadhtml("http://60.232.1.10:83/likoushan_c/views/p/smessagedetail.html?id="+eid+"&");
        }

        bdinit();

//        findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                mLocationClient.stop();
//                mHandler.post(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        // TODO Auto-generated method stub
//                        //调用JS中的 函数，当然也可以不传参
//                        content.loadUrl("javascript:androidCallJS('顺便传个参数给JS！')");
//                    }
//                });
//            }
//        });

//                content.reload();
        Intent service = new Intent(MainActivity.this, FirstService.class);
        startService(service);
    }

    public static boolean isrun(){

        if(null!=mLocationClient){
            return mLocationClient.isStarted();
        }else{
            return true;
        }
    }

    public static void torun(){
        mLocationClient.start();
    }

    private  String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private void loadhtml(String dizhi){
//        String url="http://60.232.1.10:83/likoushan_c/views/p/index.html"+"?userid="+"11"+"&sign="+sign
        String url=dizhi+"userid="+userid+"&sign="+sign
                +"&imei="+ LikoushanApi.imei+"&auth="+type+"&channel_type=2"+"&api=1.0";
        Log.d("xing", "首地址" + url);
        content = (WebView) findViewById(R.id.content);
        content.getSettings().setJavaScriptEnabled(true);

        content.addJavascriptInterface(new JavaScriptinterface(this),
                "android");
        content.setWebChromeClient(new WebChromeClient());
//		content.loadData(url, "text/html; charset=UTF-8",
//				null);
        if (Build.VERSION.SDK_INT >= 19) {
            content.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
        content.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                view.loadUrl(url);
                return true;
            }
        });
        content.loadUrl(url);
    }

    private void bdinit(){
        //百度
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(this);
        //注册监听函数
        //myListener.onReceiveLocation();
        initLocation();
//        百度开始
        mLocationClient.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0) {
            granted = grantResults[0] == PackageManager.PERMISSION_GRANTED;//是否授权，可以根据permission作为标记
        }
    }
//
//    @Override
//    public void onPermissionsGranted(int requestCode, List<String> perms) {
//
//    }
//
//    @Override
//    public void onPermissionsDenied(int requestCode, List<String> perms) {
//
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//            new AppSettingsDialog.Builder(this).build().show();
//        }
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
//            // Do something after user returned from app settings screen, like showing a Toast.
//            Toast.makeText(MainActivity.this, "权限申请成功", Toast.LENGTH_SHORT)
//                    .show();
//        }
//    }


    public class JavaScriptinterface {
        Context context;
        public JavaScriptinterface(Context c) {
            context= c;
        }
        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public String showToast(String ssss) {

            if(ssss.equals("0")){
                chuanornot="0";
                Log.d("xing","下班了哈");
//                ToastUtil.showToast(MainActivity.this, "下班");
//                mLocationClient.stop();
            }
            if(ssss.equals("1")){
                chuanornot="1";
//                ToastUtil.showToast(MainActivity.this, "上班");
                mLocationClient.start();
            }
            if(ssss.equals("3")){

                Log.d("xing","进来3了咩");
                first="1";
                mLocationClient.stop();
                bdinit();
//                mHandler.post(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        // TODO Auto-generated method stub
//                        //调用JS中的 函数，当然也可以不传参
//                        Log.d("xing","上传坐标咩");
//                        content.loadUrl("javascript:androidCallJS('"+jingdu+","+weidu+"')");
//                    }
//                });
            }
            if(ssss.equals("9")){
                out();
            }
            return "调用成功了";

        }
        @JavascriptInterface
        public String getloc() {

            Log.d("xing", jingdu+","+weidu);
            return jingdu+","+weidu;
        }
    }

    private void out(){
        Sharedpreference.sd.clear();
        Sharedpreference.sd.commit();
        finish();
        LikoushanApi.clearregid(MainActivity.this, xiaomiregid,sign,userid, new ResponseInterface() {
            @Override
            public void onSuccess(Object obj) {

                Regidbean bean = (Regidbean) obj;
                if (bean.getResult_code().equals("1")) {
                    MiPushClient.unregisterPush(MainActivity.this);
                    ToastUtil.showToast(MainActivity.this, "退出了");
                    Sharedpreference.sd.clear();
                    Sharedpreference.sd.commit();
                    finish();
                }
            }

            @Override
            public void onFailed(String obj) {

            }

            @Override
            public void onMessage(String msg) {

            }
        });
    }

    private long mExitTime;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span=15000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }

    public static void sendId(Context context){
        Log.d("xing", "这里面搞" + xiaomiregid);

        LikoushanApi.sendregid(context, xiaomiregid,sign,userid, new ResponseInterface() {
            @Override
            public void onSuccess(Object obj) {

            }

            @Override
            public void onFailed(String obj) {

            }

            @Override
            public void onMessage(String msg) {

            }
        });
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        //获取定位结果

        jingdu=String.valueOf(location.getLongitude());
        weidu=String.valueOf(location.getLatitude());

        if(first.equals("1")){
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    //调用JS中的 函数，当然也可以不传参
                    Log.d("xing","上传坐标咩");
                    content.loadUrl("javascript:androidCallJS('"+jingdu+","+weidu+"')");
                }
            });
//            mLocationClient.stop();
            first="0";
        }
        if(chuanornot.equals("1")){
            uploadloaction(String.valueOf(location.getLongitude()),String.valueOf(location.getLatitude()));
        }

        Log.d("xing", "位置" + jingdu+"     "+weidu);

    }

    @Override
    public void onConnectHotSpotMessage(String s, int i) {

    }

    private void uploadloaction(String latitude,String longititude) {

//        ToastUtil.showToast(MainActivity.this, "在传");

        LikoushanApi.sendLocation(MainActivity.this, sign, userid, latitude, longititude, new ResponseInterface() {
            @Override
            public void onSuccess(Object obj) {
                UploadBean bean = (UploadBean) obj;
                if (bean.getSign_resultc_code().equals("0")) {

//                    ToastUtil.showToast(MainActivity.this, "签名错误，请重新登陆");
//                    Sharedpreference.sd.clear();
//                    finish();
                } else if (bean.getResult_code().equals("1")) {

                    //ToastUtil.showToast(MainActivity.this, "上传成功");
                }
            }

            @Override
            public void onFailed(String obj) {

            }

            @Override
            public void onMessage(String msg) {

            }
        });

    }

    /*Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:

                    uploadloaction();

                    break;

            }
        }
    };*/

    @Override
    public void finish() {
        super.finish();
        mLocationClient.stop();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String eid=intent.getStringExtra("msgID");
        loadhtml("http://60.232.1.10:83/likoushan_c/views/p/smessagedetail.html?id="+eid+"&");
    }
}

